#!/bin/bash
#
# Snippets for documents.

# TODO: These should be set by "snip" I think.
set -o errexit
set -o nounset

# TODO: This should be shared with AppBuild somehow.
jsont() {
  ../_tmp/deps/jsont.tin "$@"
}

# A plain <pre> section -- markdown generates <pre><code>, which I don't want.
pre() {
  echo '<pre>'
  cat
  echo '</pre>'
}

toc() { 
  local option=${1:-}
  echo '<div id="toc">'
  if test "$option" = "no-heading"; then
    echo -n
  else
    echo '  <div id="toctitle">Table of Contents</div>'
  fi
  cat <<EOF
  <noscript><p><b>(omitting table of contents without JavaScript)</b></p></noscript>
</div>
EOF
}

# Prints grammar to stdout.
grammar() {
  # NOTE: This is already indented by 4 for markdown?  Should you explicitly
  # indent with sed?
  # TODO: We also need syntax highlighting here.
  local name=$1
  case $name in
    cre)
      echo '<pre>'
      python ../annex/cre_parse.py
      echo '</pre>'
      ;;
    tpe)
      echo '<pre>'
      cat ../annex/tpe.tpe
      echo '</pre>'
      ;;
    *)
      echo Unknown grammar $name
      exit 1
      ;;
  esac
}

# Insert help
annex-help() {
  cd .. && (
    echo '<pre>'
    ./run.sh annex --help
    echo '</pre>'
  )
}

# Shows HTML for a CRE, with RE equivalent.
cre-and-re() {
  local name=$1
  python ../tests/cre_examples.py $name | jsont cre-example.jsont
}

# Shows short HTML for a CRE, with RE equivalent.
cre-short() {
  local name=$1
  python ../tests/cre_examples.py $name | jsont cre-short.jsont
}

cre-only() {
  local name=$1
  python ../tests/cre_examples.py $name | jsont cre-only.jsont
}

# HELPER: Hack pygments output to be compatible with markdown embedded HTML... sigh.
div-on-own-line() {
  sed -e 's|\(<div class="highlight">\)|&\n|g' \
      -e 's|\(</div>\)|\n&|g'
}

# Syntax highlighting with pygments.
syntax() {
  local lexer=$1
  # Read from stdin.
  pygmentize -f html -l $lexer | div-on-own-line
}

# Insert syntax table
syntax-table() {
  ./make_syntax.py | jsont syntax-table.jsont
}

"$@"
